package com.oneboot.bbsdemo.controller.common;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Slf4j
public class ErrorPageController implements ErrorController {


    private static ErrorPageController errorPageController;

    private final static String ERROR_PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    private boolean getTraceParameter(HttpServletRequest request) {
        String trace = request.getParameter("trace");
        log.warn("trace:" + trace);

        if (trace == null) {
            return false;
        }

        // 值错-> 结果对，值对—>结果错   错就是错，对就不用响应错误页
        return !"false".equals(trace.toLowerCase());
    }

    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        ServletWebRequest webRequest = new ServletWebRequest(request);
        return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
    }

    public HttpStatus getStatus(HttpServletRequest request) {
        // 从请求中获取HTTP错误状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

        // 检查状态码是否为空
        if (statusCode != null) {
            try {

                // 尝试将状态码转换为HttpStatus枚举值
                return HttpStatus.valueOf(statusCode);
            } catch (Exception e) {}
        }

        // 如果状态码为空或转换失败，返回内部服务器错误状态码
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}
